<template>
  <div class="date-section">
    <h3 class="section-title">参观日期</h3>
    <div class="date-options">
      <div 
        class="date-option" 
        :class="{ active: selectedDate === date.value, disabled: !date.available }"
        v-for="date in dateOptions" 
        :key="date.value"
        @click="selectDate(date)"
      >
        <div class="date-label">{{ date.label }}</div>
        <div class="date-value">{{ date.display }}</div>
        <div class="date-check" v-if="selectedDate === date.value">✓</div>
      </div>
      <div class="date-option more-option" @click="showDatePicker">
        <div class="date-label">更多</div>
        <div class="date-arrow">></div>
      </div>
    </div>

    <!-- 日期选择弹窗 -->
    <el-dialog
      v-model="datePickerVisible"
      title="请选择日期"
      width="90%"
      class="date-picker-dialog"
    >
      <div class="calendar-container">
        <div class="calendar-header">
          <button class="month-nav" @click="previousMonth" :disabled="currentMonth <= 6">‹</button>
          <h4>{{ currentYear }}年{{ String(currentMonth).padStart(2, '0') }}月</h4>
          <button class="month-nav" @click="nextMonth" :disabled="currentMonth >= 7">›</button>
        </div>
        <div class="calendar-grid">
          <div class="calendar-weekdays">
            <span v-for="day in weekdays" :key="day">{{ day }}</span>
          </div>
          <div class="calendar-dates">
            <div 
              class="calendar-date"
              :class="{ 
                active: calendarDate.selected, 
                available: calendarDate.available && !calendarDate.isPlaceholder,
                disabled: !calendarDate.available && !calendarDate.isPlaceholder
              }"
              :data-placeholder="calendarDate.isPlaceholder"
              v-for="calendarDate in calendarDates" 
              :key="calendarDate.date || Math.random()"
              @click="!calendarDate.isPlaceholder && selectCalendarDate(calendarDate)"
            >
              {{ calendarDate.day }}
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button type="primary" @click="confirmDateSelection" size="large" class="confirm-date-btn">
          确认
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElDialog } from 'element-plus'

// Props
const props = defineProps({
  selectedDate: {
    type: String,
    default: ''
  }
})

// Emits
const emit = defineEmits(['update:selectedDate', 'dateChanged'])

// 获取当前显示月份
const getCurrentMonth = () => {
  if (props.selectedDate) {
    // 如果有选中日期，显示选中日期的月份
    return new Date(props.selectedDate).getMonth() + 1
  }
  
  // 否则根据当前日期判断应该显示哪个月
  const now = new Date()
  const currentMonth = now.getMonth() + 1
  
  // 如果当前是2025年6月之前，默认显示6月
  // 如果当前是2025年7月之后，默认显示7月
  // 如果当前是2025年6-7月，显示当前月份
  if (now.getFullYear() < 2025 || (now.getFullYear() === 2025 && currentMonth < 6)) {
    return 6
  } else if (now.getFullYear() > 2025 || (now.getFullYear() === 2025 && currentMonth > 7)) {
    return 7
  } else {
    return currentMonth
  }
}

// 响应式数据
const datePickerVisible = ref(false)
const currentMonth = ref(getCurrentMonth()) // 当前月份
const currentYear = ref(2025) // 当前年份

// 监听选中日期变化
watch(() => props.selectedDate, (newDate) => {
  if (newDate) {
    const selectedMonth = new Date(newDate).getMonth() + 1
    if (selectedMonth >= 6 && selectedMonth <= 7) {
      currentMonth.value = selectedMonth
    }
  }
})

// 星期数组
const weekdays = ['日', '一', '二', '三', '四', '五', '六']

// 日历数据
const calendarDates = ref([])

// 获取当前日期
const getCurrentDate = () => {
  return new Date() // 使用真实当前日期
}

// 获取格式化日期字符串
const formatDate = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 获取显示用的日期字符串
const getDisplayDate = (date) => {
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${month}-${day}`
}

// 检查日期是否在可预约范围内（展馆开放期间：2025年6月25日-7月22日）
const isDateBookable = (date) => {
  const targetDate = new Date(date)
  const startDate = new Date(2025, 5, 25) // 2025年6月25日
  const endDate = new Date(2025, 6, 23) // 2025年7月22日
  const currentDate = getCurrentDate()
  
  // 目标日期必须在展馆开放期间内，且不能早于今天
  return targetDate >= startDate && 
         targetDate < endDate && 
         targetDate >= new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate())
}

// 获取日期不可预约的原因
const getDateUnavailableReason = (date) => {
  const targetDate = new Date(date)
  const startDate = new Date(2025, 5, 25) // 2025年6月25日
  const endDate = new Date(2025, 6, 23) // 2025年7月22日
  const currentDate = getCurrentDate()
  const today = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate())
  
  if (targetDate < today) {
    return '该日期已过期，无法预约'
  } else if (targetDate < startDate) {
    return '展馆将于2025年6月25日开放，请选择开放日期'
  } else if (targetDate > endDate) {
    return '展馆于2025年7月22日结束，请选择展期内日期'
  }
  
  return '该日期不可预约'
}

// 动态日期选项
const dateOptions = computed(() => {
  const currentDate = getCurrentDate()
  
  // 如果没有选中日期，默认基于当前日期显示今明后天
  if (!props.selectedDate) {
    const today = new Date(currentDate)
    const tomorrow = new Date(currentDate)
    tomorrow.setDate(tomorrow.getDate() + 1)
    const dayAfterTomorrow = new Date(currentDate)
    dayAfterTomorrow.setDate(dayAfterTomorrow.getDate() + 2)
    
    return [
      { label: '今天', value: formatDate(today), display: getDisplayDate(today), available: isDateBookable(today) },
      { label: '明天', value: formatDate(tomorrow), display: getDisplayDate(tomorrow), available: isDateBookable(tomorrow) },
      { label: '后天', value: formatDate(dayAfterTomorrow), display: getDisplayDate(dayAfterTomorrow), available: isDateBookable(dayAfterTomorrow) }
    ]
  }
  
  // 检查选中的日期是否是今明后天
  const today = formatDate(currentDate)
  const tomorrow = formatDate(new Date(currentDate.getTime() + 24 * 60 * 60 * 1000))
  const dayAfterTomorrow = formatDate(new Date(currentDate.getTime() + 2 * 24 * 60 * 60 * 1000))
  
  const isToday = props.selectedDate === today
  const isTomorrow = props.selectedDate === tomorrow
  const isDayAfterTomorrow = props.selectedDate === dayAfterTomorrow
  
  if (isToday || isTomorrow || isDayAfterTomorrow) {
    // 如果选中的是今明后天，显示今明后天
    const todayDate = new Date(currentDate)
    const tomorrowDate = new Date(currentDate)
    tomorrowDate.setDate(tomorrowDate.getDate() + 1)
    const dayAfterTomorrowDate = new Date(currentDate)
    dayAfterTomorrowDate.setDate(dayAfterTomorrowDate.getDate() + 2)
    
    return [
      { label: '今天', value: formatDate(todayDate), display: getDisplayDate(todayDate), available: isDateBookable(todayDate) },
      { label: '明天', value: formatDate(tomorrowDate), display: getDisplayDate(tomorrowDate), available: isDateBookable(tomorrowDate) },
      { label: '后天', value: formatDate(dayAfterTomorrowDate), display: getDisplayDate(dayAfterTomorrowDate), available: isDateBookable(dayAfterTomorrowDate) }
    ]
  } else {
    // 如果选中的是其他日期，显示选中日期及其后两天
    const selectedDateObj = new Date(props.selectedDate)
    const nextDay = new Date(selectedDateObj)
    nextDay.setDate(nextDay.getDate() + 1)
    const dayAfterNext = new Date(selectedDateObj)
    dayAfterNext.setDate(dayAfterNext.getDate() + 2)
    
    return [
      { 
        label: '选中日期', 
        value: props.selectedDate, 
        display: getDisplayDate(selectedDateObj), 
        available: isDateBookable(selectedDateObj) 
      },
      { 
        label: '次日', 
        value: formatDate(nextDay), 
        display: getDisplayDate(nextDay), 
        available: isDateBookable(nextDay) 
      },
      { 
        label: '第三天', 
        value: formatDate(dayAfterNext), 
        display: getDisplayDate(dayAfterNext), 
        available: isDateBookable(dayAfterNext) 
      }
    ]
  }
})

// 选择日期
const selectDate = (date) => {
  if (!date.available) {
    const reason = getDateUnavailableReason(date.value)
    ElMessage.error(reason)
    return
  }
  emit('update:selectedDate', date.value)
  emit('dateChanged', date.value)
}

// 显示日期选择器
const showDatePicker = () => {
  generateCalendarDates()
  datePickerVisible.value = true
}

// 上一个月
const previousMonth = () => {
  if (currentMonth.value > 6) {
    currentMonth.value--
    generateCalendarDates()
  }
}

// 下一个月
const nextMonth = () => {
  if (currentMonth.value < 7) {
    currentMonth.value++
    generateCalendarDates()
  }
}

// 生成日历数据
const generateCalendarDates = () => {
  const dates = []
  const year = currentYear.value
  const month = currentMonth.value
  
  // 获取当月第一天是星期几（0-6，0表示星期日）
  const firstDayOfMonth = new Date(year, month - 1, 1).getDay()
  
  // 获取当月天数
  const daysInMonth = new Date(year, month, 0).getDate()
  
  // 添加上个月的空白日期
  for (let i = 0; i < firstDayOfMonth; i++) {
    dates.push({
      day: '',
      date: '',
      available: false,
      selected: false,
      isPlaceholder: true
    })
  }
  
  // 生成当月的日期
  for (let i = 1; i <= daysInMonth; i++) {
    const date = new Date(year, month - 1, i)
    const dateString = `${year}-${String(month).padStart(2, '0')}-${String(i).padStart(2, '0')}`
    const available = isDateBookable(date)
    
    dates.push({
      day: i,
      date: dateString,
      available: available,
      selected: props.selectedDate === dateString,
      isPlaceholder: false
    })
  }
  
  calendarDates.value = dates
}

// 选择日历日期
const selectCalendarDate = (calendarDate) => {
  if (!calendarDate.available) {
    const reason = getDateUnavailableReason(calendarDate.date)
    ElMessage.error(reason)
    return
  }
  
  // 重置之前的选择
  calendarDates.value.forEach(date => date.selected = false)
  calendarDate.selected = true
  emit('update:selectedDate', calendarDate.date)
}

// 确认日期选择
const confirmDateSelection = () => {
  if (!props.selectedDate) {
    ElMessage.error('请选择日期')
    return
  }
  
  datePickerVisible.value = false
  emit('dateChanged', props.selectedDate)
  ElMessage.success('日期选择成功')
}

// 初始化
onMounted(() => {
  generateCalendarDates()
})
</script>

<style scoped>
/* 日期选择区域 */
.date-section {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 4px 20px rgba(0,0,0,0.1);
}

.section-title {
  margin: 0 0 15px 0;
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.date-options {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 12px;
}

.date-option {
  position: relative;
  border: 2px solid #e8eaf6;
  border-radius: 10px;
  padding: 15px 10px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background: white;
}

.date-option.active {
  border-color: #667eea;
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
}

.date-option.disabled {
  opacity: 0.5;
  cursor: not-allowed;
  background: #f5f5f5;
  color: #999;
  position: relative;
}

.date-option.disabled::after {
  content: '不可选';
  position: absolute;
  bottom: 2px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 10px;
  color: #f44336;
  font-weight: bold;
}

.date-option:not(.disabled):hover {
  border-color: #667eea;
  transform: translateY(-2px);
}

.date-label {
  font-size: 12px;
  margin-bottom: 5px;
  opacity: 0.8;
}

.date-value {
  font-size: 14px;
  font-weight: bold;
}

.date-check {
  position: absolute;
  top: 5px;
  right: 5px;
  background: rgba(255,255,255,0.3);
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: bold;
}

.more-option {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.date-arrow {
  font-size: 18px;
  font-weight: bold;
  color: #667eea;
}

/* 日历样式 */
.calendar-container {
  padding: 20px;
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.month-nav {
  background: #f8f9ff;
  border: 1px solid #e8eaf6;
  border-radius: 50%;
  width: 36px;
  height: 36px;
  font-size: 16px;
  color: #667eea;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.month-nav:hover:not(:disabled) {
  background: #e8eaf6;
  transform: scale(1.05);
}

.month-nav:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.calendar-header h4 {
  text-align: center;
  margin: 0;
  font-size: 18px;
  color: #333;
}

.calendar-weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 5px;
  margin-bottom: 10px;
}

.calendar-weekdays span {
  text-align: center;
  font-size: 14px;
  color: #666;
  padding: 10px;
}

.calendar-dates {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 5px;
}

.calendar-date {
  aspect-ratio: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.calendar-date[data-placeholder="true"] {
  background: transparent;
  cursor: default;
}

.calendar-date.available {
  background: #f8f9ff;
  color: #333;
}

.calendar-date.available:hover {
  background: #e8eaf6;
}

.calendar-date.active {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
}

.calendar-date.disabled {
  color: #ccc;
  cursor: not-allowed;
  background: #f5f5f5;
  position: relative;
}

.calendar-date.disabled::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 10%;
  right: 10%;
  height: 1px;
  background: #f44336;
  transform: translateY(-50%);
}

.confirm-date-btn {
  width: 100%;
  background: linear-gradient(135deg, #667eea, #764ba2);
  border: none;
}

/* 弹窗样式 */
:deep(.date-picker-dialog) {
  border-radius: 15px;
  overflow: hidden;
}

:deep(.date-picker-dialog .el-dialog__header) {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  padding: 20px;
  margin: 0;
}

:deep(.date-picker-dialog .el-dialog__title) {
  color: white;
  font-weight: bold;
}

/* 通用弹窗关闭按钮样式 */
:deep(.date-picker-dialog .el-dialog__headerbtn .el-dialog__close) {
  color: white;
  font-size: 18px;
  transition: all 0.3s ease;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

:deep(.date-picker-dialog .el-dialog__headerbtn .el-dialog__close:hover) {
  background: rgba(255, 255, 255, 0.2);
  transform: scale(1.1);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

:deep(.date-picker-dialog .el-dialog__headerbtn) {
  top: 20px;
  right: 20px;
  width: 32px;
  height: 32px;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .date-options {
    grid-template-columns: repeat(4, 1fr);
    gap: 8px;
  }
  
  .date-option {
    padding: 12px 8px;
  }
  
  .date-label, .date-value {
    font-size: 12px;
  }
  
  .calendar-container {
    padding: 15px;
  }
  
  .month-nav {
    width: 32px;
    height: 32px;
    font-size: 14px;
  }
}
</style> 